package com.nowcoder.community.controller;

import com.nowcoder.community.contant.Entity;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.service.DisccusPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class HomeController {
    @Autowired
    private UserService userService;

    @Autowired
    private DisccusPostService disccusPostService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    // 显示帖子
    // 需要根据帖子中的 userId 查询用户以显示用户名
    /**
     * @param order 0-最新 1-最热
     * */
    @GetMapping({"/index", "/"})
    public String homePage(Model model, Page page,
        @RequestParam(name = "order", defaultValue = "0") int order
    ){
        page.setPath("/index?order=" + order);
        page.setLimit(10);
        page.setRows(disccusPostService.findDiscussPostRows(0));

        List<DiscussPost> posts = disccusPostService.findDiscussPost(0, page.getOffset(), page.getLimit(), order == 1);
        List<Map<String, Object>> discussPosts = new ArrayList<>();

        if (posts != null){
            for (DiscussPost post: posts){
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);
                map.put("user", userService.findUserById(post.getUserId()));
                map.put("likeCount", likeService.countEntityLikes(Entity.DISCUSS_POST, post.getId()));
                map.put("likeStatus", hostHolder.getUser() == null ? 0 : likeService.likeStatus(hostHolder.getUser().getId(), Entity.DISCUSS_POST, post.getId()));
                discussPosts.add(map);
            }
        }

        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("order", order);
        return "/index";
    }
}
